package com.sy.olddriver.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 这个过滤器用于保存每个线程每次的请求和响应对象
 * 保持一个完整的请求处理过程中同一个线程所具有的请求对象和响应对象
 * 通过ThreadLocal保留每次的请求和响应对象
 * 使得这个对象可以从Servlet中一直保持到后面的Handler、Service等中去
 *
 * @author Administrator
 */
public class ServletHolder implements Filter {
    private static ThreadLocal<HttpServletRequest> curRequest = new ThreadLocal<>();
    private static ThreadLocal<HttpServletResponse> curResponse = new ThreadLocal<>();

    /**
     * 获取当前的请求对象
     *
     * @return 请求对象
     */
    public static HttpServletRequest getCurRequest() {
        return curRequest.get();
    }

    /**
     * 获取当前的响应对象
     *
     * @return 响应对象
     */
    public static HttpServletResponse getCurResponse() {
        return curResponse.get();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        //在Servlet执行以前，将请求对象和响应对象通过ThreadLocal保存每个线程对应的副本
        curRequest.set(req);
        curResponse.set(res);
        chain.doFilter(req, res);
        //此次请求结束以后，从ThreadLocal中移除此次的请求和响应对象
        curRequest.remove();
        curResponse.remove();
    }

    @Override
    public void destroy() {

    }
}
